package com.sky.controller.admin;


import com.sky.entity.Admin;
import com.sky.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

// 如果前端和后端端口不同，需要加 @CrossOrigin 或使用全局 CORS 配置
@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    // 注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Admin requestBody) {
        if (requestBody.getUsername() == null || requestBody.getPassword() == null) {
            return ResponseEntity.badRequest().body(
                    new Result(0, "用户名或密码为空")
            );
        }

        Admin newAdmin = adminService.registerAdmin(
                requestBody.getUsername(),
                requestBody.getPassword()
        );
        if (newAdmin == null) {
            // 表示用户名已存在
            return ResponseEntity.ok(new Result(0, "该用户名已被注册"));
        }

        // 注册成功
        return ResponseEntity.ok(new Result(1, "注册成功"));
    }

    // 登录（示例）
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Admin requestBody) {
        if (requestBody.getUsername() == null || requestBody.getPassword() == null) {
            return ResponseEntity.badRequest().body(
                    new Result(0, "用户名或密码为空")
            );
        }

        Admin admin = adminService.loginAdmin(
                requestBody.getUsername(),
                requestBody.getPassword()
        );
        if (admin == null) {
            return ResponseEntity.ok(new Result(0, "用户名或密码错误"));
        }
        return ResponseEntity.ok(new Result(1, "登录成功"));
    }

    // 用于示例的返回对象
    static class Result {
        public int code;
        public String message;

        public Result(int code, String message) {
            this.code = code;
            this.message = message;
        }
    }
}